<template>
  <div class="roles-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">系统管理——角色管理</h1>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-section">
      <div class="action-left">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
        <el-button @click="handleQueryRecent">
          <el-icon><Clock /></el-icon>
          查询近3天
        </el-button>
      </div>
      
      <div class="action-right">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD"
        />
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="tableData"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="序号" width="80" />
        
        <el-table-column prop="name" label="角色名称" width="200" />
        <el-table-column prop="description" label="角色描述" min-width="300" />
        <el-table-column prop="operatorCount" label="操作人数" width="100" />
        <el-table-column prop="createdAt" label="添加时间" width="120" />
        
        <el-table-column label="显示" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              修改
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>
        
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Clock } from '@element-plus/icons-vue'
import api from '@/services/api'
import dayjs from 'dayjs'

export default {
  name: 'Roles',
  components: {
    Plus, Clock
  },
  setup() {
    const loading = ref(false)
    const submitLoading = ref(false)
    const dialogVisible = ref(false)
    const dialogTitle = ref('新增角色')
    const formRef = ref()
    const dateRange = ref([])
    
    // 表格数据
    const tableData = ref([
      {
        id: 1,
        name: '产品设计工程师',
        description: '产品设计所有功能权限、数据权限、操作权限',
        operatorCount: 2,
        createdAt: '2030-10-9',
        status: true
      },
      {
        id: 2,
        name: '研发工程师',
        description: '商品功能权限、数据权限、操作权限',
        operatorCount: 8,
        createdAt: '2030-10-9',
        status: true
      },
      {
        id: 3,
        name: '市场工程师',
        description: '授权系统管理用户、角色',
        operatorCount: 1,
        createdAt: '2030-10-9',
        status: true
      },
      {
        id: 4,
        name: '销售工程师',
        description: '授权系统管理用户、角色',
        operatorCount: 1,
        createdAt: '2030-10-9',
        status: true
      },
      {
        id: 5,
        name: '财务',
        description: '功能权限、数据权限、操作权限',
        operatorCount: 2,
        createdAt: '2030-10-9',
        status: false
      },
      {
        id: 6,
        name: '运营工程师',
        description: '授权库存管理、商品',
        operatorCount: 2,
        createdAt: '2030-10-9',
        status: false
      },
      {
        id: 7,
        name: '客服后勤',
        description: '系统库存管理、产品、商品',
        operatorCount: 1,
        createdAt: '2030-10-9',
        status: false
      }
    ])
    
    // 分页
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 7
    })
    
    // 表单数据
    const form = reactive({
      id: null,
      name: '',
      description: '',
      status: true
    })
    
    // 表单验证规则
    const rules = reactive({
      name: [
        { required: true, message: '请输入角色名称', trigger: 'blur' }
      ],
      description: [
        { required: true, message: '请输入角色描述', trigger: 'blur' }
      ]
    })
    
    // 获取角色列表
    const fetchRoles = async () => {
      loading.value = true
      try {
        const response = await api.get('/roles', {
          params: {
            page: pagination.currentPage,
            size: pagination.pageSize,
            startDate: dateRange.value?.[0],
            endDate: dateRange.value?.[1]
          }
        })
        
        if (response.data.code === 200) {
          tableData.value = response.data.data || []
          pagination.total = response.data.data.total || 0
        }
      } catch (error) {
        ElMessage.error('获取角色列表失败')
        console.error('获取角色列表失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 查询近3天
    const handleQueryRecent = () => {
      const endDate = dayjs().format('YYYY-MM-DD')
      const startDate = dayjs().subtract(3, 'day').format('YYYY-MM-DD')
      dateRange.value = [startDate, endDate]
      fetchRoles()
    }
    
    // 新增
    const handleAdd = () => {
      dialogTitle.value = '新增角色'
      resetForm()
      dialogVisible.value = true
    }
    
    // 编辑
    const handleEdit = (row) => {
      dialogTitle.value = '修改角色'
      Object.assign(form, {
        id: row.id,
        name: row.name,
        description: row.description,
        status: row.status
      })
      dialogVisible.value = true
    }
    
    // 删除
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除这个角色吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await api.delete(`/roles/${row.id}`)
        if (response.data.code === 200) {
          ElMessage.success('删除成功')
          fetchRoles()
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }
    
    // 状态变化
    const handleStatusChange = async (row) => {
      try {
        const response = await api.put(`/roles/${row.id}`, {
          status: row.status
        })
        if (response.data.code === 200) {
          ElMessage.success('状态更新成功')
        } else {
          // 回滚状态
          row.status = !row.status
        }
      } catch (error) {
        // 回滚状态
        row.status = !row.status
        ElMessage.error('状态更新失败')
      }
    }
    
    // 分页大小变化
    const handleSizeChange = (size) => {
      pagination.pageSize = size
      fetchRoles()
    }
    
    // 当前页变化
    const handleCurrentChange = (page) => {
      pagination.currentPage = page
      fetchRoles()
    }
    
    // 提交表单
    const handleSubmit = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
      } catch (error) {
        return
      }
      
      submitLoading.value = true
      
      const isEdit = !!form.id
      
      try {
        const url = isEdit ? `/roles/${form.id}` : '/roles'
        const method = isEdit ? 'put' : 'post'
        
        const response = await api[method](url, form)
        if (response.data.code === 200) {
          ElMessage.success(isEdit ? '更新成功' : '创建成功')
          dialogVisible.value = false
          fetchRoles()
        }
      } catch (error) {
        const errorMessage = error.response?.data?.message || (isEdit ? '更新失败' : '创建失败')
        ElMessage.error(errorMessage)
      } finally {
        submitLoading.value = false
      }
    }
    
    // 重置表单
    const resetForm = () => {
      Object.assign(form, {
        id: null,
        name: '',
        description: '',
        status: true
      })
    }
    
    // 关闭对话框
    const handleDialogClose = () => {
      resetForm()
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    }
    
    onMounted(() => {
      fetchRoles()
    })
    
    return {
      loading,
      submitLoading,
      dialogVisible,
      dialogTitle,
      formRef,
      dateRange,
      tableData,
      pagination,
      form,
      rules,
      fetchRoles,
      handleQueryRecent,
      handleAdd,
      handleEdit,
      handleDelete,
      handleStatusChange,
      handleSizeChange,
      handleCurrentChange,
      handleSubmit,
      handleDialogClose
    }
  }
}
</script>

<style scoped>
.roles-page {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.action-section {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-left {
  display: flex;
  gap: 10px;
}

.action-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .action-section {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }
  
  .action-left {
    flex-wrap: wrap;
  }
  
  .action-right {
    justify-content: center;
  }
}
</style>
